import React, { Component } from 'react';
import { Modal, Form, Input,Radio,Select,DatePicker,Popconfirm ,Row,Col,Button,Icon,Upload, message} from 'antd';
import styles from '../item.less';
import moment from 'moment'
import * as ContractModel from '../../model/contract';
import * as CustomerModel from '../../model/customer';
import * as UserModel from '../../model/user';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
const FormItem = Form.Item;
const Option = Select.Option;
const dateFormat = 'YYYY-MM-DD';
var _ = require( 'underscore');
class _Modal extends Component {
  constructor(props) {
    super(props);
    let _orders = {}
    Array.from(props.record.orders||[]).map(d=>{
        d.id = d.id || 'key-'+parseInt(Math.random()*10000)
        _orders[d.id] = d
    })

    this.state = {
      visible: false,
      orders:_orders,
      mes:'',
      name:'',
      address:'',
      customer_num:'',
      record:props.record ||{contract_num:''}
    };
    // if(props.record !== null ){
    //     if(props.record.contract_num !==''){
    //         this.getItem(props.record.contract_num);
    //     }
    // }
  }

  showModelHandler =async (e) => {
    if (e) e.stopPropagation();
      if(this.props.record !== null ){
          if(this.props.record.contract_num !==''){
              this.getItem(this.props.record.contract_num);
          }
      this.setState({
        visible: true,
        mes:'',
        name:'',
        address:'',
        customer_num:''
      });
    }else{
      this.props.form.resetFields()
    }
  }

  hideModelHandler = () => {
    this.setState({
      visible: false,
        mes:'',
        name:'',
        address:'',
        customer_num:''
    });
    this.props.form.resetFields()
  };
  handleSubmit = async(e) => {
      let comps = Object.values(this.state.orders)
      comps.map(d=>{
          delete d.id
      })
      let return2Father = this.props.return2Father
      let item = Object.assign({},this.props.record)
      //查找推送给相应财务
      // let to_user = []
      // let filter = {'role':{$in:['accountant','accountant_manager']}};

      // let users = await UserModel.fetch({
      //   filter:filter,
      //   limit:999999,
      //   startPos: 0,
      // })
      // users.data.list.map(d=>to_user.push(d.cnum));
      this.props.form.validateFields((err, values) => {
        if (!err) {
            item = Object.assign(item,values);
            item.brand_num=item.brand_num.toLowerCase();
            item.components = comps;
            // item.to_user = to_user;
            // item.note = this.state.name+"的采购单添加成功";
            // item.action = "添加"
            return2Father(item)
            this.hideModelHandler()
        }
      });

  };
  async getItem(e){
    if(e !== undefined){
      let res =await ContractModel.fetch({filter:{offline_num:e}});
      if(res.data.count ==0 ){
        this.setState({mes:'获取客户信息失败', record:{contract_num:''}});
        message.error(' 获取合同号失败')
      }else{
          let ctItem = res.data.list[0]
          let res1 =await CustomerModel.getByNum(ctItem.customer_num);
          if(res1.status == 'success' && res1.data.item){
              let nes={};
              nes=Object.assign(this.state.record,{mes:'',customer_num:res1.data.item.cnum,name:res1.data.item.name,address:res1.data.item.full_address});
              this.setState(nes);
          }else{
            this.setState({mes:'获取客户信息失败',record:{contract_num:''}});
            message.error(' 获取客户信息失败')
          }

      }
    }
  }
  onChange=(date, dateString)=>{
  console.log(date, dateString);
}
  render() {
    const { children } = this.props;
    const { getFieldDecorator,getFieldValue} = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
  const child = [];
  let _u = JSON.parse(localStorage.user);
  const arr = Object.keys(JSON.parse(_u.role_data || '{}'))

  for (let key of arr) {
    child.push(<Option key={key}>{key}</Option>);
  }
    return (
      <span>
        <span onClick={this.showModelHandler}>
          { children }
        </span>
        <Modal
          title={'cnum' in this.state.record ? '修改：'+this.state.record.cnum:'新建一条采购单信息'}
          visible={this.state.visible}
          onCancel={this.hideModelHandler}
          onOk={this.handleSubmit}
          width="80%"
        >
            <Form layout="horizontal" >
                  <FormItem className={styles.FormItem} {...formItemLayout} label="品牌" >
                    {getFieldDecorator('brand_num', {rules: [{required: true, message: '必须填写'}],initialValue: this.state.record.brand_num})(
                        <Select  mode="combobox">
                          {child}
                        </Select>
                    )  }
                  </FormItem>
                  <FormItem className={styles.FormItem} {...formItemLayout} label="采购专员" >
                    {getFieldDecorator('purchase_user', {initialValue: this.state.record.purchase_user,rules: [{required: true, message: '必须填写'}]})(<Input size="small" />)  }
                  </FormItem>
                  <FormItem className={styles.FormItem} {...formItemLayout} label="采购经理" >
                    {getFieldDecorator('purchase_master', {initialValue: this.state.record.purchase_master,rules: [{required: true, message: '必须填写'}]})(<Input size="small" />)  }
                  </FormItem>
                  <FormItem className={styles.FormItem} {...formItemLayout} label="合同编号" hasFeedback>
                    {getFieldDecorator('contract_num', {initialValue: this.state.record.contract_num,rules: [{required: true, message: '必须填写'}]})(
                          <span><Input size="small" defaultValue={this.state.record.contract_num} onBlur={()=>this.getItem(getFieldValue('contract_num'))} />
                          <span>{this.state.mes}</span></span>)}
                  </FormItem>
                  <FormItem className={styles.FormItem} {...formItemLayout} label="客户编号" >
                    {getFieldDecorator('customer_num', {initialValue: this.state.customer_num})(<Input size="small" disabled />)  }
                  </FormItem>
                  <FormItem className={styles.FormItem} {...formItemLayout} label="客户姓名" >
                    {getFieldDecorator('name', {initialValue: this.state.name})(<Input size="small" disabled />)  }
                  </FormItem>
                  <FormItem className={styles.FormItem} {...formItemLayout} label="客户地址" >
                    {getFieldDecorator('address', {initialValue: this.state.address})(<Input size="small" disabled/>)  }
                  </FormItem>
                  <FormItem className={styles.FormItem} {...formItemLayout} label="销售原价" >
                    {getFieldDecorator('sale_originalPrice', {initialValue: this.state.record.sale_originalPrice,rules: [{required: true, message: '必须填写'}]})(<Input size="small" />)  }
                  </FormItem>
                  <FormItem className={styles.FormItem} {...formItemLayout} label="销售折扣" >
                    {getFieldDecorator('sale_discount', {initialValue: this.state.record.sale_discount,rules: [{required: true, message: '必须填写'}]})(<Input size="small" />)  }
                  </FormItem>
                  <FormItem className={styles.FormItem} {...formItemLayout} label="采购币种" >
                    {getFieldDecorator('currency_num', {initialValue: this.state.record.currency_num,rules: [{required: true, message: '必须选择'}]})(
                        <Radio.Group size="small">
                            {['美元','欧元','人民币'].map(v=><Radio key={v} value={v}>{v}</Radio>)}
                        </Radio.Group>
                    )  }
                  </FormItem>
                  <FormItem className={styles.FormItem} {...formItemLayout} label="销售折后价" >
                    {getFieldDecorator('contract_money', {initialValue: this.state.record.contract_money,rules: [{required: true, message: '必须填写'}]})(<Input size="small"/>)  }
                  </FormItem>
                  <FormItem className={styles.FormItem} {...formItemLayout} label="计划到货时间" >
                    {getFieldDecorator('plan_arrive_at',{initialValue: moment(this.state.record.plan_arrive_at,dateFormat)._isValid===true?moment(this.state.record.plan_arrive_at,dateFormat):null})( <DatePicker  onChange={()=>this.onChange} />)  }
                  </FormItem>
                  <FormItem className={styles.FormItem} {...formItemLayout} label="下单日期" >
                    {getFieldDecorator('order_at',{initialValue: moment(this.state.record.order_at,dateFormat)._isValid===true?moment(this.state.record.order_at,dateFormat):null})(<DatePicker onChange={()=>this.onChange} />)  }
                  </FormItem>
            </Form>
        </Modal>
      </span>
    );
  }
}

export default Form.create()(_Modal);
